/*
 * cbuffer.c
 *
 *  Created on: 18.10.2009
 *      Author: fregat
 */

# include "cbuffer.h"
# include <malloc.h>
# include <memory.h>

void *_read (CBUFFER *pcb);
void _write (CBUFFER *pcb, const void *pv);
void incr_tail (CBUFFER *);
void incr_head (CBUFFER *);


CBUFFER *cb (unsigned char size, unsigned char unit_size)
{
	CBUFFER *pret = malloc (sizeof (CBUFFER));
	pret->buffer = malloc (size * unit_size);
	pret->head = pret->tail = 0;
	pret->read = _read;
	pret->write = _write;
	pret->size = size * unit_size;
	pret->unit_size = unit_size;
	return pret;
}

void _cb (CBUFFER *pcb)
{
	free (pcb->buffer);
	free (pcb);
}

void *_read (CBUFFER *pcb)
{
	void *pres;
	if (pcb->head == pcb->tail)
		// buffer leer
		return 0;
	pres = pcb->buffer+pcb->tail;
	incr_tail (pcb);
	return pres;
}

void _write (CBUFFER *pcb, const void *pv)
{
	void *ptmp = pcb->buffer + pcb->head;
	memcpy (ptmp, pv, pcb->unit_size);
	incr_head (pcb);
	return;
}

void incr_head (CBUFFER *pcb)
{
	pcb->head += pcb->unit_size;
	if (pcb->head >= pcb->size)
		pcb->head = 0;
	if (pcb->head == pcb->tail)
		//buffer over
		pcb->tail += pcb->unit_size;
	if (pcb->tail >= pcb->size)
		pcb->tail = 0;
}

void incr_tail (CBUFFER *pcb)
{
	if (pcb->tail == pcb->head)
		//buffer leer
		return;

	pcb->tail += pcb->unit_size;
	if (pcb->tail >= pcb->size)
		pcb->tail = 0;
}



